from django.shortcuts import render
from .serializers import BrandSer
from .models import Brand
from rest_framework.views import APIView
from rest_framework.response import Response
import os
from day1 import settings
# Create your views here.
class Upload(APIView):
    def post(self,request):
        """上传图片"""
        files = request.FILES.get('file')
        # 把图片写入到指定的位置，并保存
        # 获取图片路径前缀
        files_dir = settings.STATICFILES_DIRS[0]
        # 拼接图片的路由
        file_name = files_dir + files.name
        # 把图片写入到指定路径文件中
        with open(file_name,'wb') as f:
            # 读取图片的字节节流
            f.write(files.file.read())
        return Response({'msg':'上传成功','code':200,'files_path':files.name})


class AddBrand(APIView):
    def post(self,request):
        name = request.data.get('name')
        first = request.data.get('first')
        logo = request.data.get('logo')
        try:
            Brand.objects.get(name=name)
            return Response({'msg':'该品牌已存在','code':204})
        except Exception as e:
            Brand.objects.create(name=name,first_name=first,logo=logo)
            return Response({'msg':'添加成功','code':200})


class GetBrand(APIView):
    def get(self,request):
        num = int(request.query_params.get('num'))
        pagesize = int(request.query_params.get('pagesize'))
        data = Brand.objects.all()[((num-1)*pagesize):(num*pagesize)]
        ser = BrandSer(data,many=True)
        return Response({'data':ser.data,'count':Brand.objects.all().count()})

class PutBrand(APIView):
    def get(self,request,edit_id):
        try:
            data = Brand.objects.get(id=edit_id)
            ser = BrandSer(data)
            return Response(ser.data)
        except Exception as e:
            print(e)
            return Response({'msg':'没有该品牌','code':204})
    def put(self,request,edit_id):
        name = request.data.get('name')
        first = request.data.get('first')
        logo = request.data.get('logo')
        try:
            data = Brand.objects.get(id=edit_id)
            data.name = name
            data.first_name=first
            data.logo = logo
            data.save()
            return Response({'msg':'修改成功','code':200})
        except Exception as e:
            print(e)
            return Response({'msg':'未找到该品牌','code':204})
    def delete(self,request,edit_id):
        try:
            Brand.objects.get(id=edit_id).delete()
            return Response({'msg':'删除成功','code':200})
        except Exception as e:
            print(e)
            return Response({'msg':'未找到该品牌','code':204})


